package com.fire.web.modules.all.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.fire.common.mybatis.mvc.wrapper.EntityWrapper;
import com.fire.common.utils.FastJsonUtils;
import com.fire.common.utils.StringUtils;
import com.fire.web.modules.all.constant.ErrorCodeConstants;
import com.fire.web.modules.all.entity.*;
import com.fire.web.modules.all.request.AddSiteReq;
import com.fire.web.modules.all.service.*;
import com.fire.web.modules.sso.service.IOAuthService;
import com.fire.web.modules.sys.entity.Menu;
import com.fire.web.modules.sys.service.IMenuService;
import com.fire.web.modules.sys.service.IRoleService;
import com.fire.web.security.shiro.realm.UserRealm;
import com.fire.web.utils.MenuTreeHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.fire.web.modules.all.utils.TokenUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/site")
public class SiteController extends CrudController<ISiteService, SiteModel> {
    private static final Logger LOGGER = LoggerFactory.getLogger(SiteController.class);

    @Autowired
    private IMenuService menuService;
    @Autowired
    private ISiteService siteService;
    @Autowired
    private IOAuthService oAuthService;
	@Autowired
	private IRoleService roleService;


    /**
     * 根据页码和每页记录数，以及查询条件动态加载数据
     *
     * @param request
     * @throws IOException
     */
    @GetMapping("/list")
    public AjaxResult list(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
	    LOGGER.info("==================查询站点开始==================");
        AjaxResult ajaxResult;
        try {
            String token = TokenUtil.getToken(request,response);
            UserRealm.Principal principalByAccessToken = oAuthService.getPrincipalByAccessToken(token);
	        String username = principalByAccessToken.getUsername();
	        String userId = principalByAccessToken.getId();
	        Page<SiteModel> pageBean = null;
	        // 加入条件
	        EntityWrapper<SiteModel> entityWrapper = new EntityWrapper<>();
	        // 默认查询参数
	        Integer page = 1;
	        Integer limit = 10;
	        String selectColumn = "";
	        String columnValue = "";
	        Object tempObj = null;
	        tempObj = params.get("page");
	        if(tempObj != null){
		        page = Integer.parseInt(tempObj.toString());
		        tempObj = null;
	        }
	        tempObj = params.get("limit");
	        if(tempObj != null){
		        limit = Integer.parseInt(tempObj.toString());
		        tempObj = null;
	        }
	        tempObj = params.get("selectColumn");
	        if(tempObj != null){
		        selectColumn = (String)tempObj;
		        tempObj = null;
	        }
	        tempObj = params.get("columnValue");
	        if(tempObj != null){
		        columnValue = (String)tempObj;
		        tempObj = null;
	        }
	        Page<SiteModel> pageObj = new Page<>(page,limit);
	        if(StringUtils.isNotBlank(selectColumn)||StringUtils.isNotBlank(columnValue)){
		        entityWrapper.like(selectColumn,columnValue);

	        }
	        String admin = "admin";
            if(!admin.equals(username)){
	            LOGGER.info("非admin用户"+username+"  UserId:" + userId);
	            String authority = roleService.queryAuthorityByUserId(userId);
	            pageBean = siteService.querySiteAuthorOwnList(pageObj,authority,userId,entityWrapper);
            }
			if(admin.equals(username)){
				LOGGER.info("admin用户");
				pageBean = siteService.selectPage(pageObj,entityWrapper);
			}
            ajaxResult = new AjaxResult(ErrorCodeConstants.SUCCESS, "获取成功", pageBean, "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("SiteController.list().error  错误为：", e);
            ajaxResult = new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统内部错误", "系统内部错误");
        }
        //替换tips
        ajaxResult = replaceTips(ajaxResult);
	    LOGGER.info("==================查询站点结束==================");
        return ajaxResult;
    }

	/**
	 * 增加站点
	 * @param req
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping("/addSite")
	@ResponseBody
    public AjaxResult addSite(AddSiteReq req, HttpServletRequest request, HttpServletResponse response) {
		LOGGER.info("==================增加站点开始==================");
		AjaxResult ajaxResult;
		try {
			String token = TokenUtil.getToken(request,response);
			UserRealm.Principal principalByAccessToken = oAuthService.getPrincipalByAccessToken(token);
			String username = principalByAccessToken.getUsername();
			String adminId = principalByAccessToken.getId();

			// 加入条件
			ajaxResult = siteService.addSiteInSmartThing(req,adminId);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("SiteController.page().error  错误为：", e);
			ajaxResult = new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统内部错误", "系统内部错误");
		}
		//替换tips
		ajaxResult = replaceTips(ajaxResult);
		LOGGER.info("==================增加站点结束==================");
		return ajaxResult;
    }

	/**
	 * 删除
	 *
	 * @return
	 */
	@DeleteMapping("/deleteSite/{siteToken}")
	@ResponseBody
	public AjaxResult deleteSite(@PathVariable("siteToken") String siteToken) {
		LOGGER.info("==================删除站点开始==================");
		AjaxResult ajaxResult;
		try {
			ajaxResult = siteService.deleteSiteInSmartThing(siteToken);
		} catch (Exception e) {
			LOGGER.error("SiteController.deleteSite().error  错误为：", e);
			ajaxResult = new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统内部错误", "系统内部错误");
		}
		//替换tips
		ajaxResult = replaceTips(ajaxResult);
		LOGGER.info("==================删除站点结束==================");

		return ajaxResult;
	}

	/**
	 * 更新
	 *
	 * @return
	 */
	@PostMapping("/updateSite")
	@ResponseBody
	public AjaxResult updateSite(AddSiteReq req) {
		LOGGER.info("==================更新站点开始==================");
		AjaxResult ajaxResult;
		try {
			ajaxResult = siteService.updateSiteInSmartThing(req);
		} catch (Exception e) {
			LOGGER.error("SiteController.updateSite().error  错误为：", e);
			ajaxResult = new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统内部错误", "系统内部错误");
		}
		//替换tips
		ajaxResult = replaceTips(ajaxResult);
		LOGGER.info("==================更新站点结束==================");

		return ajaxResult;
	}

    /**
     * 获得菜单列表
     *
     * @throws IOException
     */
    @GetMapping(value = "getSiteMenus")
    public void getMenus(){
        List<Menu> treeNodeList = menuService.selectTreeList(new EntityWrapper<Menu>().eq("t.independency","site"));
        List<MenuTreeHelper.MenuTreeNode> menuTreeNodes = MenuTreeHelper.create().sort(treeNodeList);
        FastJsonUtils.print(menuTreeNodes);
    }
}
